package top.gcl.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import top.gcl.dao.GoodsMapper;
import top.gcl.entity.Goods;
import top.gcl.redis.RedisUtil;


import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
public class GoodsServiceImpl {
    @Resource
    private GoodsMapper mapper;
    @Resource
    private RedisUtil redisUtil;

    /**
     * 根据id查询商品详情
     *
     * 如果redis缓存中读取出的goods是null，那么就查询mysql数据库，查询后放入redis。
     * 如果在mysql中根据id获取不到商品，就说明没有该商品，为了防止缓存穿透，将空的字符串放到redis缓存中
     *
     */
    public Goods getGoodsById(String id )
    {
        String redisKeyGoods="goods_"+id;
        String redisKeyGoodsLike="goods_likr_"+id;
        //从redis缓存中获取goods的内容
        Object goodsObj=redisUtil.get(redisKeyGoods);
        Goods goods=null;
        if(goodsObj==null)
        {
            goods=mapper.getGoodsById(id);
            if(goods!=null)
            {
                if(goods.getImgPath()==null)
                {
                    goods.setImgPath("");
                }
                redisUtil.set(redisKeyGoods,goods);
            }else
                {
                    redisUtil.set(redisKeyGoods,"SB");
                }
            redisUtil.expire(redisKeyGoods,60*60*6);
        }else if("SB".equals(goodsObj))
        {
            goods=null;
        }else
            {
                goods= (Goods) goodsObj;
                Integer like=(Integer)redisUtil.get(redisKeyGoodsLike);
                if(like!=null)
                {
                    goods.setLikeNum(like);
                }
            }
        return goods;
    }

    /**
     * 添加商品
     * @param goods
     */

    public void sendNotice(Goods goods) {
        String uuid= UUID.randomUUID().toString().replace("-","");
        goods.setId(uuid);
        mapper.createGoods(goods);
    }

    /**
     * 查询所有商品
     * @param pageNum
     * @param pageSize
     * @return
     */
    public PageInfo<Goods> list(int pageNum, int pageSize){
        Page page= PageHelper.startPage(pageNum,pageSize,true);
        //开始执行查询
        List list =mapper.list();
        PageInfo<Goods> pageInfo=new PageInfo<Goods>(list,page.getPages());

        return pageInfo;
    }

    /**
     * 点赞和取消
     * 加1   incr
     * 减1   decr
     */
    public int like(String id , int num)
    {
        String redisKeyGoodsLike="goods_like_"+id;
        int like=0;
        if(num>0)
        {
            like=(int)redisUtil.incr(redisKeyGoodsLike,num);

        }else
            {
                like=(int) redisUtil.decr(redisKeyGoodsLike,-num);
                if(like<0)
                {
                    like=0;
                    redisUtil.set(redisKeyGoodsLike,0);
                }
            }
        return like;
    }


}
